package com.zed.api.common;

import java.io.IOException;

/**
 * 序列化器
 *
 * @author Zed
 */
public interface Serializer {

    /**
     * {@code target}对象进行序列化,对象所关联的类及本身要实现{@link java.io.Serializable}接口
     *
     * @param target {@link Object},序列化对象
     * @return {@link byte[]},字节数组
     * @throws IOException 序列化时出现的例外
     */
    byte[] serial(Object target) throws IOException;

    /**
     * 对字节数据进行反序列化成对象
     *
     * @param bytes {@link byte[]},字节数据
     * @return {@link Object},反序列后的对象
     * @throws IOException            IO例外
     * @throws ClassNotFoundException 找不到类例外
     */
    Object deSerial(byte[] bytes) throws IOException, ClassNotFoundException;

    /**
     * 对字节数据进行反序列化对象并转换成对应的投影类
     *
     * @param bytes    {@link byte[]},字节数据
     * @param typeCast {@link Class},类型
     * @return {@link T}
     * @throws IOException            IO例外
     * @throws ClassNotFoundException 找不到类例外
     */
    default <T> T deSerial(byte[] bytes, Class<T> typeCast) throws IOException, ClassNotFoundException {
        Object result = this.deSerial(bytes);
        if (result != null && typeCast != null) {
            if (typeCast.isAssignableFrom(result.getClass())) {
                return typeCast.cast(result);
            }
        }
        return null;
    }
}
